package com.suxin.security.builder;

import com.suxin.security.configure.SecurityConfigure;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Tang
 * @classname AbstractConfigureSecurityBuilder
 * @description [ 更细力度的控制 ]
 * @date 2022/8/16 16:17
 */
public abstract class AbstractConfigureSecurityBuilder<O, B extends SecurityBuilder<O>> extends AbstractSecurityBuilder<O> {

    private final List<SecurityConfigure<O, B>> securityConfigureList = new LinkedList<>();

    protected LinkedHashMap<Class<? extends SecurityConfigure<O, B>>, List<SecurityConfigure<O, B>>>
            configures = new LinkedHashMap<>();

    @Override
    public O doBuilder() throws Exception {

        beforeInit();
        init();

        beforeConfigure();
        configure();

        return preformBuild();
    }

    /**
     * preformBuild
     * @return
     */
    protected abstract O preformBuild();

    protected void init() throws Exception {
        for (SecurityConfigure<O, B> configure : getSecurityConfigureList()) {
            configure.init((B)this);
        }
    }

    protected void configure() throws Exception {
        for (SecurityConfigure<O, B> configure : getSecurityConfigureList()) {
            configure.configure((B)this);
        }
    }

    @SuppressWarnings("unchecked")
    public <C extends SecurityConfigure<O, B>> C getConfigurer(Class<C> cClass) {
        List<SecurityConfigure<O, B>> securityConfigures = configures.get(cClass);
        return (C)securityConfigures.get(0);
    }

    public <C extends SecurityConfigure<O, B>> C removeConfigure(Class<C> cClass) {
        return null;
    }

    protected void beforeConfigure(){

    }

    protected void beforeInit(){

    }

    public List<SecurityConfigure<O, B>> getSecurityConfigureList() {
        return securityConfigureList;
    }
}
